/****************************************************************
 * <strong>MFAccountFilter</strong>
 *
 * <p>
 * MFAccountFilter
 * </p>
 *
 * @author AndyZhang 2012  cnet2001@163.com
 * @version 0.1
 * ToDo:
 ***************************************************************/

package com.thinkwide.data.filter;

import com.thinkwide.data.core.MFPath;
import com.thinkwide.data.core.MFString;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class MFAccountFilter implements Filter {
    public static final String userkey = "@user";
    private String path;
    private static MFURLManager manager;

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        String url = ((HttpServletRequest) request).getRequestURI();
        //MFDebug.println(url);

        if (url.indexOf(".jsp") < 0) {
            chain.doFilter(request, response);
            return;
        }

        if (MFString.compareNoCase(url, path)) {
            chain.doFilter(request, response);
            return;
        }

        if (manager == null) {
            try {
                manager = new MFURLManager();
                String path = MFPath.getDirFromClassLoader() + MFPath.fseparator + "mfurl.xml";
                manager.loadConfig(path);
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
        }

        try {
            if (!manager.needUser(url)) {
                chain.doFilter(request, response);
                return;
            } else {
                Object user = ((HttpServletRequest) request).getSession().getAttribute(userkey);

                if (user != null) {
                    chain.doFilter(request, response);

                } else {
                    ((HttpServletResponse) response).sendRedirect(path);
                    return;
                }
            }

        } catch (Throwable ex) {
            ex.printStackTrace();
        }


    }

    public void init(FilterConfig config) throws ServletException {
        path = config.getInitParameter("url");
    }

}